﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form2 : Form
    {
        Socket clientSocket;
        public Form2()
        {
            InitializeComponent();
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //这里的ip地址，端口号都是服务端绑定的相关数据。
            Thread thread = new Thread(Connect);
            thread.Start();
        }
        void Connect()
        {
            while (true)
            {
                try
                {
                    clientSocket.Connect("127.0.0.1", 7100);
                    Thread thread = new Thread(Receive);
                    thread.Start();
                }
                catch { }
                Thread.Sleep(500);
            }
        }
        void Receive()
        {
            while (true)
            {
                try
                {
                    Byte[] msg = new byte[1024];
                    if (clientSocket.Receive(msg) > 0)
                    {
                        textBox1.Text = Encoding.UTF8.GetString(msg).Trim('\0', ' ');
                    }
                }
                catch
                {
                    clientSocket.Close();
                    break;
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Byte[] msg = Encoding.UTF8.GetBytes(textBox2.Text);
            clientSocket.Send(msg);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            clientSocket.Close();
            this.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Form1 f = new Form1();
            f.Show();
        }
    }
}
